package com.ungao.tools.generator.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Objects;
import java.util.Properties;

public abstract class AbstractConnection implements IConnection {

    /**
     * 数据库连接对象
     */
    protected Connection connection;

    protected AbstractConnection(Connection connection) {
        Objects.requireNonNull(connection, "the jdbc connection is not to bu null!");
        this.connection = connection;
    }

    protected AbstractConnection(String url, String username, String password, String driver) {
        Objects.requireNonNull(url, "the connection url is not to bu null!");
        Objects.requireNonNull(username, "the connection username is not to bu null!");
        Objects.requireNonNull(password, "the connection password is not to bu null!");
        Objects.requireNonNull(driver, "the jdbc driver is not to bu null!");
        try {
            Class.forName(driver);
            this.connection = DriverManager.getConnection(url, this.connectProperties(username, password));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    //开启数据库表备注
    private Properties connectProperties(String username, String password) {
        Properties props = new Properties();
        props.setProperty("user", username);
        props.setProperty("password", password);
        props.setProperty("remarks", "true");
        props.setProperty("useInformationSchema", "true");
        return props;
    }

    @Override
    public void close() throws Exception {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
    }
}
